<script setup lang="ts">
import {  onUnmounted, onMounted,ref,watch } from "vue"
import { editWmsLayer } from "@/api/wmslayer"
import * as mars3d from "mars3d"
import { useTabStore } from '@/store/tab';
import { getGeojson as getGeojsonApi } from '@/api/tab';
import { useUserStore } from '@/store/user';
const userStore = useUserStore();
const Cesium = mars3d.Cesium
const flag = ref(0)
const tabStore = useTabStore();
// 用于存放地球组件实例
let map: mars3d.Map // 地图对象
let wmsLayers="sytdlz:sytdlz_less";

onMounted(async ()=>{
  await initMars3d()
  await tabStore.getPostgres()
})
const emit = defineEmits(["onload"])

const initMars3d = async () => {
  map = new mars3d.Map(`mars3d-container`,  {
      scene: {
          center:{"lat":33.597926,"lng":120.187673,"alt":165588,"heading":360,"pitch":-90},
          showSkyAtmosphere: false, // 关闭球周边的白色轮廓 map.scene.skyAtmosphere = false
          showSkyBox:false,
          showSun:false,
          showMoon:false,
          globe: {
              showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
              depthTestAgainstTerrain: false,
              baseColor: "#546a53"
          },
          cameraController: {
              zoomFactor: 10.0,
              minimumZoomDistance: 1,
              maximumZoomDistance: 50000000,
              enableTilt:false,
              enableZoom: true
          },
          sceneMode:Cesium.SceneMode.SCENE3D
      },
      basemaps: [{
        name: "百度影像",
        type: "gaode",
        layer: "img_d",
        show: true
      },{
        name: "天地图注记(EPSG:4326)",
        type: "tdt",
        show: false,
        zIndex: 99999,
        layer: "img_z",
        key: mars3d.Token.tiandituArr
      }],
      control: {},
      hasTerrain:false
  })

  // 开场动画
  // map.openFlyAnimation();

  // 针对不同终端的优化配置
  if (mars3d.Util.isPCBroswer()) {
    // map.zoomFactor = 2.0 // 鼠标滚轮放大的步长参数

    // IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
      map.viewer.targetFrameRate = 60 // 限制帧率
      map.scene.requestRenderMode = true // 取消实时渲染
    }
  } else {
    // map.zoomFactor = 5.0 // 鼠标滚轮放大的步长参数

    // 移动设备上禁掉以下几个选项，可以相对更加流畅
    map.scene.requestRenderMode = true // 取消实时渲染
    map.scene.fog.enabled = false
    map.scene.skyAtmosphere.show = false
    map.scene.globe.showGroundAtmosphere = false
  }

  // //二三维切换不用动画
  if (map.viewer.sceneModePicker) {
    map.viewer.sceneModePicker.viewModel.duration = 0.0
  }

  // webgl渲染失败后，刷新页面
  map.on(mars3d.EventType.renderError, async () => {
    // location.reload()
  })

  emit("onload", map)
  window.map = map
  map.unbindContextMenu()
  const distanceLegend = new mars3d.control.DistanceLegend({ right: "80px", bottom: "5vh" })
  map.addControl(distanceLegend)

  window.map.on(mars3d.EventType.wheel, (event) => {
    if (map.getCameraView().alt<=400000 ) {
      if (Math.round(map.getCameraView().alt/1000) >10) {
        map.zoomFactor = 10
      }
      else if(Math.round(map.getCameraView().alt/1000)<3){
        map.zoomFactor = 3
      }
      else{
        map.zoomFactor = Math.round(map.getCameraView().alt/1000)
      }
    }else{
      map.zoomFactor = 10
    }
  })
  // 标绘显示点图层
  window.PolyhonLayer = new mars3d.layer.GraphicLayer()
  map.addLayer(window.PolyhonLayer)
  // 标绘显示点图层
  window.plotting = new mars3d.layer.GraphicLayer()
  map.addLayer(window.plotting)
  // 测量面积
  window.measurePolygon = new mars3d.layer.GraphicLayer({
      hasEdit: true,
      isAutoEditing: true, // 绘制完成后是否自动激活编辑
      clustering: {
          enabled: true,
          pixelRange:10,
      },
  });
  map.addLayer(window.measurePolygon)
  window.measurePolygon.on(mars3d.EventType.editMovePoint, (event) => {
    if(event.editType == "polygon") {
      let graphic = event.graphic
      let area = mars3d.MeasureUtil.getArea(graphic.getCoordinates())
      let areaPF = area.toString().split('.')[0].length>6?(area/1000000).toFixed(2) + ' 平方千米\n ':area.toFixed(2) + ' 平方米\n '
      let areaMu =( area/666.666666667).toFixed(2)
      let text = "面积：" + areaPF + areaMu + " 亩"
      graphic.setStyle({
        label:{
          text:text,
          font_size:16,
          font_family:"微软雅黑",
          outline:true,
          outlineOpacity:1,
          outlineWidth:4
        }
      })
    }
  })
  window.measurePolygon.on(mars3d.EventType.drawAddPoint, (event) => {drawFirstPoint(event.cartesian)})
  window.measurePolygon.on(mars3d.EventType.drawRemovePoint, (event) => {delDrawPoint()})
  window.measurePolygon.on(mars3d.EventType.drawCreated, (event) => {endDrawPoint()})

  // 测量工具
  window.measure = new mars3d.thing.Measure({
      label: {
          color: "#ffffff",
          font_family: "楷体",
          font_size: 20,
          background: false
      }
  })
  window.map.addThing(window.measure)
  window.measure.on(mars3d.EventType.drawStart, (event) => {window.sytdlzwma.unbindHighlight()})
  window.measure.on(mars3d.EventType.drawCreated, (event) => {
    tabStore.clFlag = false
    window.sytdlzwma.bindHighlight({
      type:'polygon',
      color:'#fff',
      opacity:0.2,
      outline:true,
      outlineWidth:3,
      outlineColor:'#fff',
    })
  })

  window.measure.on(mars3d.EventType.drawAddPoint, (event) => {drawFirstPoint(event.cartesian)})
  window.measure.on(mars3d.EventType.drawRemovePoint, (event) => {delDrawPoint()})
  window.measure.on(mars3d.EventType.drawCreated, (event) => {
    endDrawPoint()
  })


  addcj()
  addWmsLayer()

  window.drawLayer = new mars3d.layer.GraphicLayer()
  window.map.addLayer(window.drawLayer)
}

const addcj = () => {
    window.cjWmslayer = new mars3d.layer.WmsLayer({
      url: "/zxchjf/geoserver/sytdlz/wms",
      layers: "sytdlz:cj",
      crs: "EPSG:2364",
      show: true,
      zIndex:98,
      parameters: {
        service:'WMS',
        version:'1.1.1',
        request:'GetMap',
        transparent: true,
        format: "image/png",
      },
    });
    map.addLayer(window.cjWmslayer)
}
// 新增点标注
const drawFirstPoint = (position) => {
  flag.value ++
  // console.log(flag.value);
  if(window.plotting.length == 0) {
    let point = new mars3d.graphic.PointEntity({
      position:position,
      style:{
        color:"#ff0000"
      }
    })
    point.addTo(window.plotting)
  }
}

const delDrawPoint = () => {
  if(flag.value > 0) {
    flag.value --
  }
  if(flag.value == 0) {
    window.plotting.clear()
  }
}

const endDrawPoint = () => {
  window.plotting.clear()
  flag.value = 0
}

// 组件卸载之前销毁mars3d实例
onUnmounted(() => {
  if (map) {
    map.destroy()
    map = null
    location.reload()
  }
  console.log("map销毁完成", map)
})

let sytdlzwma:any;
let loading:any;
let form:any;
let layerEditFlag = <boolean>false
let graphicPositions:any;
let graphicattr:any;

const addWmsLayer = async () => {
  // 确保 map 对象已初始化
    if (!map) return
    // 禁用滑块
    tabStore.isLayerLoading = true;
    // 创建entity图层
    window.wmsEdit = new mars3d.layer.GraphicLayer({
        hasEdit: true,
        isAutoEditing: true, // 绘制完成后是否自动激活编辑
    });
    map.addLayer(window.wmsEdit)
    if (sytdlzwma) {
      try {
          // 检查图层是否存在于地图中
        if (map.hasLayer(sytdlzwma)) {
            // 延迟移除操作，确保图层完全初始化
            await map.removeLayer(sytdlzwma);
            // console.log('旧的 sytdlzwma 图层已移除');
          } else {
            // console.warn('旧的 sytdlzwma 图层不在地图中');
          }
      } catch (error) {
          console.error("移除 sytdlzwma 图层时出错:", error);
      }
    }
    tabStore.queryParams.isFarm=='0'?wmsLayers = 'sytdlz:sytdlz_less':wmsLayers = 'sytdlz:sytdlzss'
    try {
      window.sytdlzwma = sytdlzwma = await new mars3d.layer.WmsLayer({
        url: "/zxchjf/geoserver/sytdlz/wms",
        layers: wmsLayers,
        crs: "EPSG:3857",
        parameters: {
          service:'WMS',
          version:'1.1.1',
          request:'GetMap',
          transparent: true,
          format: "image/png",
          cql_filter: tabStore.queryParams.farmName.length>0?
          `where contractor_name like '%${tabStore.queryParams.contractorName}%' and village_name like '%${tabStore.queryParams.villageName}%' and farm_name like '%${tabStore.queryParams.farmName}%' and town_name like '%${tabStore.queryParams.townName}%' and circulation_time like '%${tabStore.queryParams.circulationTime}%'`:
          `where contractor_name like '%${tabStore.queryParams.contractorName}%' and village_name like '%${tabStore.queryParams.villageName}%' and town_name like '%${tabStore.queryParams.townName}%' and circulation_time like '%${tabStore.queryParams.circulationTime}%'`
        },
        show: true,
        flyTo:true,
        zIndex:98,
        highlight:{
          color:'#fff',
          opacity:0.2,
          outline:true,
          outlineWidth:3,
          outlineColor:'#fff',
        }
      })
      map.addLayer(sytdlzwma)
      // 等待图层加载完成
      sytdlzwma.on('load', () => {
        // 启用滑块并显示提示框
        tabStore.isLayerLoading = false;
        // ElMessage.success('图层加载成功');
        sytdlzwma.on('click',(res:any)=>{
          if(!tabStore.clFlag) {
            sytdlzwma.unbindPopup()
            loading = ElLoading.service({ text: "正在加载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
            window.PolyhonLayer.clear()
            sytdlzwma.bindPopup(assembleHTNL(res.graphic,'viewer'),{scaleByDistance:true,animation:false,zIndex:99})
            graphicattr = res
            loading.close()
          }
        })
        sytdlzwma.on('popupOpen',(event:any)=> {
          form = JSON.parse(JSON.stringify(event.attr))
          setFunctions('viewer')
        })
      })

    } catch (error) {
      tabStore.isLayerLoading = false; // 确保在错误情况下滑块也能恢复
    }

}

const createEntity = (res:any) => {
  window.wmsEdit.clear()
  let graphic:any
  res.graphic.style={
    color:'#1d9bf0',
    opacity:.5,
    outline:true,
    outlineWidth:3,
    outlineColor:'#fff'
  }
  // res.graphic.positions.forEach((element,index) => {
  //   res.graphic.positions[index] = Cesium.Cartesian3.fromDegrees(...element)
  // });

  graphic = new mars3d.graphic.PolygonEntity(res.graphic)
  window.wmsEdit.addGraphic(graphic)
  graphic.setCallbackPositions(graphicPositions)
  graphic.flyTo()
  graphic.startEditing()
  graphic.on('editMovePoint',(event:any)=> {
    layerEditFlag = true
  })
  // 监听popup打开事件
  graphic.on('popupOpen',(event:any)=> {
    form = JSON.parse(JSON.stringify(graphic.attr))
    setFunctions('edit')
  })
  graphic.bindPopup(assembleHTNL(res.graphic,'edit'),{animation:false,zIndex:100})
  setTimeout(() => {graphic.openPopup()}, 500)
  loading.close()
}

const assembleHTNL = (graphic:any,type:any) => {
  form = JSON.parse(JSON.stringify(graphic.attr))
  let htmlStr = <string>''
  htmlStr = htmlStr + `<div class="listInfoTitle"><div style="width:70px">承包人：</div><div style="width:196px" id="cbrValue" class="value">${form.contractor_name}</div><input style="width:196px" id="cbrInput" name="" type="text" value="${form.contractor_name}"></div>`;
  htmlStr = htmlStr + `
  <div class="lineItem">
    <div class="labelName"><span>镇</span><span>名：</span></div>
    <div class="value">${form.town_name}</div>
    <input name="" type="text" value="${form.town_name}">
  </div>
  <div class="lineItem">
    <div class="labelName"><span>村</span><span>名：</span></div>
    <div class="value">${form.village_name}</div>
    <input name="" type="text" value="${form.village_name}">
  </div>
  `
  if(form.farm_name != null) {
    htmlStr = htmlStr + `
    <div class="lineItem">
      <div class="labelName"><span>农</span><span>场</span><span>名</span><span>称：</span></div>
      <div id="ncValue" class="value">${form.farm_name}</div>
      <input id="ncInput" name="" type="text" value="${form.farm_name}">
    </div>
    `
  }
  htmlStr = htmlStr + `

    <div class="lineItem">
      <div class="labelName"><span>面</span><span>积：</span></div>
      <div id="mjpfValue" class="value">${form.area}</div>
      <input style="width: 135px;" id="mjpfInput" name="" type="text" value=""><span id="bmjUnit"> ㎡</span><br />
    </div>
    <div class="lineItem">
      <div class="labelName"><span></span><span></span></div>
      <div id="mjmValue" class="value">${(form.area/666.67).toFixed(2)}</div>
      <input style="width: 135px;" id="mjmInput" name="" type="text" value=""><span id="bmjUnit"> 亩</span>
    </div>
  `
  if(userStore.roles.includes('superadmin')||userStore.roles.includes('farmAdmin')) {
    if(type == 'edit') {
      htmlStr = htmlStr + `
      <div class="button" id="tjxgBtn">
        <span>提交修改</span>
      </div>
      `
    }else {
      htmlStr = htmlStr + `
      <div class="button" id="ksbjBtn">
        <span>开始编辑</span>
      </div>
      `
    }
  }

  return htmlStr
}

const setFunctions = (type:string) => {
  try {
    let ncValue = document.getElementById('ncValue')
    let ncInput = document.getElementById('ncInput')
    if(type == 'edit') {
      ncValue!.style.display = 'none'
      ncInput!.style.display = 'block'
      ncInput!.onchange = () =>{
        form.farm_name = ncInput.value
      }
    }
  } catch (error) {}
  try {
    let cbrValue = document.getElementById('cbrValue')
    let cbrInput = document.getElementById('cbrInput')
    if(type == 'edit') {
      cbrValue!.style.display = 'none'
      cbrInput!.style.display = 'block'
      cbrInput!.onchange = () =>{
        form.contractor_name = cbrInput.value
      }
    }
  } catch (error) {}
  try {
    let mjpfValue = document.getElementById('mjpfValue')
    let mjmValue = document.getElementById('mjmValue')
    let mjpfInput = document.getElementById('mjpfInput')
    let mjmInput = document.getElementById('mjmInput')
    // if(typeof(form.area) != 'number') {
    //   form.area = mjpfValue!.innerText = mjpfInput!.value = (form.area*10000000000).toFixed(2)
    //   mjmValue!.innerText = mjmInput!.value = (form.area*10000000000/666.67).toFixed(2)
    // }else {
    //   mjpfValue!.innerText = mjpfInput!.value = form.area
    //   mjmValue!.innerText = mjmInput!.value = (form.area*10000000000/666.67).toFixed(2)
    // }
    if(type == 'edit') {
      mjpfValue!.style.display = 'none'
      mjmValue!.style.display = 'none'
      mjpfInput!.style.display = 'block'
      mjmInput!.style.display = 'block'
      mjpfInput!.onchange = () =>{
        form.area = mjpfInput.value
        mjmInput!.value = (mjpfInput.value/666.67).toFixed(2)
      }
      mjmInput!.onchange = () =>{
        form.area = mjpfInput!.value = (mjmInput.value*666.67).toFixed(2)
      }
    }
  } catch (error) {}
  try {
    let tymjValue = document.getElementById('tymjValue')
    tymjValue!.innerText = Math.round(form.project_area*100)/100
  } catch (error) {}
  try {
    let tjxgBtn = document.getElementById('tjxgBtn')
    let graphic = window.wmsEdit.graphics[0]
    tjxgBtn!.onclick = () =>{
      if(graphic.options.attr.layer != form.layer||graphic.options.area != form.area) {
        let arr = {
          gid:form.gid,
          layer:form.layer,
          area:form.area,
          farmName:form.farm_name,
          contractorName:form.contractor_name,
        }
        // -------------------------------------------------------------------------------------------------------
        let geom = graphic.toGeoJSON({closure:true,noAlt:true}).geometry
        geom.coordinates = [geom.coordinates]
        geom.type = 'MultiPolygon'
        arr.geom = JSON.stringify(geom)
        editWmsLayer(arr).then((res:any)=> {
          if(res.code === 200) {
            graphic.options.attr.layer = form.layer
            graphic.options.attr.area = form.area *1
            ElMessage({ message: res.msg, type: 'success' })
            sytdlzwma.reload()
            layerEditFlag=false
            // layerEditFlag?[sytdlzwma.reload(),layerEditFlag=false]:''
            window.wmsEdit.clear()
          }
        })
      }
    }
  } catch (error) {}
  try {
    let ksbjBtn = document.getElementById('ksbjBtn')
    ksbjBtn!.onclick = async () =>{
      await getGeojsonApi(graphicattr.attr.gid).then(res => {
        graphicPositions = JSON.parse(res.msg).coordinates[0][0]
        sytdlzwma.closeHighlight({color:'#fff',opacity:0.2,outline:true,outlineWidth:3,outlineColor:'#fff'})
      })
      createEntity(graphicattr)
    }
  } catch (error) {}
}

watch(()=>tabStore.queryParams.isFarm, (newValue, oldValue) => {
  if (tabStore.isLayerLoading) {
    ElMessage.warning('请等待图层加载完毕');
  } else {
    addWmsLayer();
  }
});

</script>

<template>
  <div :id="`mars3d-container`" class="mars3d-container">
  </div>
</template>

<style>
.mars3d-container {
  width: 100%;
  /* height: 105vh; */
  height: 105vh;
  overflow: hidden;
}
.mars3d-locationbar {
  bottom: 5vh !important;
}
.cesium-viewer {
  height: 105vh !important;
}
</style>
